using System;
using System.Web;
using System.Web.UI;
using ASPNETVN.PORTAL.Components.Configuration;
using ASPNETVN.PORTAL.Components.Configuration.Items;
using ASPNETVN.PORTAL.Components.Helpers;

namespace ASPNETVN.PORTAL.Controls
{
    public partial class Search : UserControl
    {

        protected static string GetUrl(Guid moduleID, int itemID)
        {
            Guid tabID = Guid.Empty;
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            foreach (PortalDataSet.TabRow tab in ds.Tab.Rows)
            {
                foreach (PortalDataSet.ModuleRow module in tab.GetModuleRows())
                {
                    if (module.ID == moduleID)
                    {
                        return string.Format("~/Default.aspx?tabid={0}&mid={1}&itemid={2}&page=Detail", tab.ID, moduleID, itemID);
                    }
                }
            }
            return string.Format("~/Default.aspx");
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                if (Request.QueryString["value"] != null)
                {
                    txtSearchText.Text = Server.UrlDecode(Request.QueryString["value"]);
                    string searchText = Server.UrlDecode(Request.QueryString["value"]);
                    dlItems.DataSource = SearchHelper.Search(searchText);
                    dlItems.DataBind();
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/Search.aspx?value={0}", Server.UrlEncode(txtSearchText.Text.Trim())));
        }

        protected void dlItems_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                string[] s = e.CommandArgument.ToString().Split(';');
                Response.Redirect(GetUrl(new Guid(s[0]), Convert.ToInt32(s[1])));
            }
        }
    }
}